package com.application.chiettinhdienluc.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.adapter.DanhMucNhanVienAdapter;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.db.NhanVienDataSource;
import com.application.chiettinhdienluc.model.ChietTinhModel;
import com.application.chiettinhdienluc.model.NguoiDungModel;
import com.application.chiettinhdienluc.rsclient.DataConnDetector;
import com.application.chiettinhdienluc.rsclient.RsGetClient;


public class DanhMucNhanVienActivity extends SherlockFragmentActivity {

	private Resources res;
	private ListView chiettinhListView;
	DanhMucNhanVienAdapter dataAdapter;

	private ArrayList<NguoiDungModel> listvattuModel = new ArrayList<NguoiDungModel>();
	private NhanVienDataSource ndDataSource = new NhanVienDataSource();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.danh_muc_nhan_vien_listview);
		res = getResources();

		ActionBar actionbar = getSupportActionBar();

		if (actionbar != null) {
			actionbar.setTitle(res
					.getString(R.string.str_title_viewlist_nhanvien));
			actionbar.setDisplayHomeAsUpEnabled(true);
			actionbar.setDisplayShowHomeEnabled(true);

		}
		chiettinhListView = (ListView) findViewById(R.id.chiettinhList);
		// chiettinhListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		dataAdapter = new DanhMucNhanVienAdapter(DanhMucNhanVienActivity.this,
				listvattuModel);
		chiettinhListView.setAdapter(dataAdapter);
		
		loadNguoiDung();
	}	

	private void loadNguoiDung() {
		if (listvattuModel != null)
			listvattuModel.clear();

		listvattuModel = ndDataSource.loadNguoidung();
		dataAdapter.setItemList(listvattuModel);
		dataAdapter.notifyDataSetChanged();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		switch (itemId) {
		case android.R.id.home:
			finish();
			break;
		case ID_ACTION_SYNC:			
			
			DataConnDetector detector = new  DataConnDetector(MainApplication.getAppContext());
			if (detector.isConnectingToInternet()) {
				getDanhMucNhanVien();
			}
			else
			{
				Toast.makeText(MainApplication.getAppContext(), R.string.no_connection_message, Toast.LENGTH_SHORT).show();
							
			}		

			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private final int ID_ACTION_SYNC = 1;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, ID_ACTION_SYNC, Menu.NONE, "Sync")
				.setIcon(R.drawable.download_icon)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		return true;
	}

	@Override
	public void onBackPressed() {
		finish();
	}

	private void getDanhMucNhanVien() {

		try {

			RsGetDanhMucNhanVienTask task = new RsGetDanhMucNhanVienTask();
			task.execute();

		} catch (Exception e) {
			e.printStackTrace();

		}

	}

	JSONArray messages = null;
	JSONObject json = null;
	ArrayList<HashMap<String, String>> messageList = null;

	private class RsGetDanhMucNhanVienTask extends
			AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {

			RsGetClient jParser = new RsGetClient();
			// http://192.168.1.46:46685
			String baseUrl = MainApplication.getServerURL();
			String url = baseUrl + "/ctrs/resources/danhmucnhanvien/"
					+ MainApplication.getMaDonViQuanLy();

			messages = jParser.getJSONFromUrl(url);

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			// Log.i(TAG, messages.toString());
			storeDanhMucNhanVien();

		}

		@Override
		protected void onPreExecute() {
			// Log.i(TAG, "onPreExecute");

		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// Log.i(TAG, "onProgressInsert");
		}

	}

	protected void storeDanhMucNhanVien() {
		try {

			int j = 1;
			// looping through All Contacts
			for (int i = 0; i < messages.length(); i++) {

				JSONObject c = messages.getJSONObject(i);

				NguoiDungModel ct = new NguoiDungModel();

				ct.set_TenDangNhap(c.getString("tenDangNhap"));
				ct.set_TenNguoiDung(c.getString("tenNguoiDung"));
				ct.set_PhanQuyen(c.getString("phanQuyen"));
				ct.set_MaDonViQuanLy(c.getString("maDviqly"));
				ct.set_MaNVien(c.getString("maNvien"));
				ct.set_MatKhau("a");
			

				boolean existed = false;

				existed = ndDataSource.checkNguoiDungExist(ct.get_MaNVien());

				if (!existed) {
					
					long id = ndDataSource.insert(ct);						
				}
				else {
					ndDataSource.update(ct);
				}
					 

			}
            
			loadNguoiDung();
			
			Toast.makeText(MainApplication.getAppContext(),
					res.getString(R.string.str_nhanvien_download_finish), Toast.LENGTH_SHORT)
					.show();

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

}
